#include "mecameraworker.h"
#include <QDebug>

MeCameraWorker::MeCameraWorker(QObject* parent)
    : QObject(parent)
    , m_isAcquiring(false)
    , m_acquisitionInterval(1000)
{
    m_acquisitionTimer = new QTimer(this);
    m_acquisitionTimer->setSingleShot(true);
    connect(m_acquisitionTimer, &QTimer::timeout, this, &MeCameraWorker::acquisitionLoop);
}

MeCameraWorker::~MeCameraWorker()
{
    stopAcquisition();
    disconnectCamera();
}

void MeCameraWorker::initialize()
{
    // 初始化代码可以在这里添加
    qDebug() << "Camera worker initialized";
}

void MeCameraWorker::connectCamera(const QString& ipAddress)
{
    QMutexLocker locker(&m_mutex);

    if (m_camera.IsOpen()) {
        emit cameraOpened(false, "相机已经连接");
        return;
    }

    std::string ip = ipAddress.toStdString();
    qDebug() << "Attempting to connect to camera with IP:" << ipAddress;

    if (m_camera.Open(ip)) {
        m_cameraConnected = true;
        emit cameraOpened(true, "相机连接成功");
        qDebug() << "Camera connected successfully";
    } else {
        m_cameraConnected = false;
        emit cameraOpened(false, "相机连接失败");
        qDebug() << "Camera connection failed";
    }
}

bool MeCameraWorker::isCameraConnected()
{
    return m_camera.IsOpen();
}

bool MeCameraWorker::isAcquiring() const
{
     return m_isAcquiring;
}

void MeCameraWorker::startAcquisition(int intervalMs)
{
    QMutexLocker locker(&m_mutex);

    if (m_isAcquiring) {
        return;
    }

    m_acquisitionInterval = intervalMs;
    m_isAcquiring = true;

    emit acquisitionStarted();

    // 立即开始第一次采集
    QTimer::singleShot(0, this, &MeCameraWorker::acquisitionLoop);
}

void MeCameraWorker::stopAcquisition()
{
    QMutexLocker locker(&m_mutex);

    if (!m_isAcquiring) {
        return;
    }

    m_isAcquiring = false;
    m_acquisitionTimer->stop();

    emit acquisitionStopped();
}

void MeCameraWorker::triggerSingleShot()
{
    QMutexLocker locker(&m_mutex);

    s_Image3dS frame;
    if (m_camera.SoftwareTrigger(frame, 5000)) {
        emit frameAcquired(frame);
    } else {
        emit errorOccurred("Single shot trigger failed");
    }
}

void MeCameraWorker::disconnectCamera()
{
    stopAcquisition();
    m_camera.Close();
    emit cameraClosed();
}

void MeCameraWorker::acquisitionLoop()
{
    QMutexLocker locker(&m_mutex);

    if (!m_isAcquiring) {
        return;
    }

    // 采集一帧
    s_Image3dS frame;
    if (m_camera.SoftwareTrigger(frame, 5000)) {
        emit frameAcquired(frame);
    } else {
        emit errorOccurred("Frame acquisition failed");
    }

    // 安排下一次采集
    if (m_isAcquiring) {
        m_acquisitionTimer->start(m_acquisitionInterval);
    }
}
